// mobile bind
// ============

define(['zepto', 'utils', 'JST'], function($, utils, JST){
  return {
    init: function(tags) {
      this.tags = tags
      this.$bindButton = $('[href="#fitness-tag-bind"]')
      this.$bindButton.length ? this.bindTagBindingAction() : void 0
    },

    /**
     * Bind action fired on clicking mobile binding button
     */
    bindTagBindingAction: function() {
      var that = this

      // On binding mobile
      this.$bindButton.on('click', function(e) {
        e.preventDefault()
        var $page = that.compileTagBindingPage(that.tags)
        $.push.transitionIn($page)
      })

      // On mobile binded
      this.$bindButton.on('choosed:fitness:tag', function(e, $page) {
        // Transition out mobile page
        //var itemDomString = $(JST.mobileItemTpl({ 'tagIds': mobile }))
        $.push.transitionOut($page, {
          beforeTransition: function() {
            var tagNames = [];
            var tagIds = [];
            $(".fitness-tag.active").each(function(e){
              tagNames.push($(this).html())
              tagIds.push($(this).data("id"))
            })
            if(tagIds.length > 0) {
              var tagInput = that.$bindButton.parent().find("input[name='tagId']");
              var tagDisplay = that.$bindButton.parent().find(".tagNames");
              that.$bindButton.parent().find(".placeholder").addClass("hide");
              $(tagInput).val(tagIds.join(","));
              $(tagDisplay).html(tagNames.join(","))
            } else {
              that.$bindButton.parent().find(".placeholder").removeClass("hide");
              that.$bindButton.parent().find(".tagNames").html("");
            }
            
          }
        })
      })
    },

    /**
     * Compile mobile binding page and return jQuery object
     */
    compileTagBindingPage: function(tags) {
      var $page = $(JST.fitnessTagBindTpl({ 'tags': tags }))
      this.bindTagBindingPageEvent($page)
      return $page
    },

    /**
     * Bind mobile binding page event
     */
    bindTagBindingPageEvent: function($page) {
      
      var that = this;
        
      // On requesting verify code
      $page.on('click', '.fitness-tag', function(e) {
        e.preventDefault()
        $(this).toggleClass('active');
      })

      // On submiting mobile
      $page.on('click', '#submit', function(e) {
        e.preventDefault();
        that.$bindButton.trigger('choosed:fitness:tag', [$page])
      })
    }
  }

})

